package com.chatdating.controller;

import com.chatdating.entity.Audit;
import com.chatdating.entity.User;
import com.chatdating.entity.dto.AuditDto;
import com.chatdating.entity.dto.LoginDto;
import com.chatdating.entity.pojo.Result;
import com.chatdating.service.AuditService;
import com.chatdating.service.AuthService;
import com.chatdating.service.UserService;
import com.chatdating.utils.EmptyUtil;
import com.chatdating.utils.SHA256Util;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/admin")
public class AdministratorController {

    private static final Logger logger = LoggerFactory.getLogger(AdministratorController.class);

    @Autowired
    private AuditService auditService;

    @Autowired
    private UserService userService;
    @Autowired
    private AuthService authService;
    /*
    管理员登录
     */
    @PostMapping("/login")
    public ResponseEntity<Result> login(@RequestBody LoginDto loginDto){

        if(EmptyUtil.isEmpty(loginDto)||EmptyUtil.isEmpty(loginDto.getName())||EmptyUtil.isEmpty(loginDto.getPassword())){
            return ResponseEntity.ok(Result.error(400,"用户名或密码为空"));
        }
        if (!"admin".equals(loginDto.getName())){
            return ResponseEntity.ok(Result.error(400,"用户名错误"));
        }

        User user = userService.findByNmme(loginDto.getName());
        String hash = user.getPassword();  //原来的 password
        String input = loginDto.getPassword();
        boolean verify = SHA256Util.verify(input,hash);

        if(!verify){
            return ResponseEntity.ok(Result.error(400,"密码错误"));
        }
        Result authenticate = authService.authenticatet(loginDto.getName(),input);
        return ResponseEntity.ok(authenticate);
    }
     /*
     审核认证中用户 信息回显
     */
    @GetMapping("/getinfo")
    public ResponseEntity<Result> getAuthenticatingUserInfo(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "3") Integer pageSize,
            @RequestParam(required = false) String username) {
        try {
            PageInfo<User> pageInfo = userService.authenticatingUser(pageNum, pageSize, username);
            return ResponseEntity.ok(Result.success(pageInfo));

        } catch (Exception e) {
            logger.error("获取当前用户信息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error(500,"系统错误，请稍后再试"));
        }
    }

    /*
    认证通过
     */
    @GetMapping("/pass")
    public ResponseEntity<Result> passAuthentication(
            @RequestParam String uname,
            @RequestParam(defaultValue = "admin") String aname,
            @RequestParam(required = false) String reason

    ) {
        AuditDto auditDto = new AuditDto(aname, uname, reason);
        try {
            userService.passAuthentication(auditDto.getUname());
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            // 定义格式化模板
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 格式化当前时间
            String formattedTime = now.format(formatter);
            Audit audit = new Audit(null, auditDto.getUname(), auditDto.getAname(), "通过",null, formattedTime);
            auditService.AddAudit(audit);
            return ResponseEntity.ok(Result.success("认证通过"));
        } catch (Exception e) {
            logger.error("用户认证通过失败，用户名: {}", auditDto.getUname(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error(500,"系统错误，请稍后再试"));
        }
    }

    /*
    认证未通过
     */
    @PostMapping("/fail")
    public ResponseEntity<Result> failAuthentication(@RequestBody AuditDto auditDto) {
        try {
            userService.failAuthentication(auditDto.getUname());
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            // 定义格式化模板
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 格式化当前时间
            String formattedTime = now.format(formatter);
            Audit audit = new Audit(null, auditDto.getUname(), auditDto.getAname(), "不通过",auditDto.getReason(), formattedTime);
            auditService.AddAudit(audit);
            return ResponseEntity.ok(Result.success("认证未通过"));
        } catch (Exception e) {
            // 打印异常日志（实际项目中使用 Logger）
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error(500,"系统错误，请稍后再试"));
        }
    }

}